#include "zy_udp.h"
#include "rtthread.h"
#include "lwip/opt.h"
#include "lwip/api.h"
#include "lwip/sys.h"
#include "lwip/igmp.h"
#include "lwip.h"
#include "gqueue.h"
#define DBG_SECTION_NAME "zy_udp"
#define DBG_LEVEL   DBG_LOG
#include "rtdbg.h"

static void Zy_Udp_Entry(void* p);

rt_thread_t tid_zyudp = RT_NULL;
static struct netconn *conn = NULL;
static struct netbuf *prcvNetBuf,*psendNetBuf;
static struct pbuf* pbufRcv;


static uint32_t rcvLen = 0;
extern ip_port_t localIP,remoteIP;



void ZY_UdpInit(void)
{
    tid_zyudp = rt_thread_create("zy udp", Zy_Udp_Entry, NULL, UDP_STACKSIZE, UDP_PRIORITY, UDP_TIMESLICE);
    if(tid_zyudp != RT_NULL){
        rt_thread_startup(tid_zyudp);
    }
}


void ZY_UdpSend(uint8_t* data, int len)
{
    err_t err;
    void* payload = NULL;
    psendNetBuf = netbuf_new();
    payload = netbuf_alloc(psendNetBuf, len);
    if(payload != NULL){
        memcpy(payload,data,len);
        err = netconn_send(conn, psendNetBuf);
        if(err != ERR_OK){
            LOG_D("send fail");
        }
        netbuf_delete(psendNetBuf);
    }
}

extern uint8_t ymPipe;
extern gqueue_t qYmRx;
rt_err_t rym_rcv_indicate(void);
ip4_addr_t groupIP;
void Zy_Udp_Entry(void* p)
{
    err_t err, recv_err;
//    igmp_init();
//    IP4_ADDR(&groupIP,239,0,0,64);
    conn = netconn_new(NETCONN_UDP);
    if (conn!= NULL)
    {
        err = netconn_bind(conn, IP_ADDR_ANY, localIP.port);
//        err = igmp_joingroup(&localIP.ip, &groupIP);
        if (err == ERR_OK)
        {
            netconn_connect(conn, &remoteIP.ip, remoteIP.port);
            netconn_set_recvtimeout(conn,10);
            while (1)
            {
                // udp 接收
                recv_err = netconn_recv(conn, &prcvNetBuf);
                if (recv_err == ERR_OK){
                    for(pbufRcv = prcvNetBuf->p;pbufRcv != NULL;pbufRcv = pbufRcv->next){
                        size_t actualLen;
                        rcvLen = pbufRcv->len;
                        gqueue_push_multiple(&qYmRx,pbufRcv->payload,rcvLen,&actualLen);
                     }
                    ymPipe = PIPE_NET;
                    rym_rcv_indicate();
                }
                netbuf_delete(prcvNetBuf);
            }
        }
        else
        {
            LOG_D("udp bind err");
            netconn_delete(conn);
        }
    }
}






